package com.zfy.servlet;

import com.zfy.entity.Category;
import com.zfy.service.CategoryService;
import com.zfy.utils.BaseServlet;
import com.zfy.utils.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.List;

@WebServlet("/CategoryServlet")
public class CategoryServlet extends BaseServlet {

    CategoryService categoryService = new CategoryService();
    public void getCates(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String cname = req.getParameter("cname");
        Integer page = Integer.parseInt(req.getParameter("page"));
        Integer limit = Integer.parseInt(req.getParameter("limit"));
         List<Category> categoryList = categoryService.getCates(cname, page, limit);
        List<Category> all = categoryService.getCates(cname, null, null);
        if(categoryList !=null && categoryList.size() > 0){
            out.println(Result.toClient(0,"",all.size(),categoryList));
        }else{
            out.println(Result.toClient(1,"无数据"));
        }
        out.flush();
        out.close();
    }


    public void addCates(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String cname = req.getParameter("cname");
        Category category = new Category();
        category.setCname(cname);
        boolean jg = categoryService.addCates(category);
        if(jg){
            out.println(Result.toClient(0,"添加成功"));
        }else{
            out.println(Result.toClient(1,"添加失败"));
        }
        out.flush();
        out.close();
    }

    public void updateCates(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String cname = req.getParameter("cname");
        int cid = Integer.parseInt(req.getParameter("cid"));
        Category category = new Category();
        category.setCname(cname);
        category.setCid(cid);
        boolean jg = categoryService.updateCates(category);
        if(jg){
            out.println(Result.toClient(0,"修改成功"));
        }else{
            out.println(Result.toClient(1,"修改失败"));
        }
        out.flush();
        out.close();
    }

    public void delCate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
